﻿using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel.User;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using ELearning.Common.CommonStr;
using System.Linq.Expressions;
using ELearning.Common.Helpers;
using ELearning.Common.Oprator;

namespace ELearning.API.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    public class UserController : BaseApiController
    {
        /// <summary>
        /// 用户操作service
        /// </summary>
        protected ESysUserService userService = new ESysUserService();

        protected EOrgService orgService = new EOrgService();

        EApplicationLogService logService => new EApplicationLogService();
        

        /// <summary>
        /// 用户角色关联操作service
        /// </summary>
        protected RRoleUserService RoleUserService = new RRoleUserService();

        EMenuService menuService = new EMenuService();

        /// <summary>
        /// 角色service
        /// </summary>
        private ERoleService roleService = new ERoleService();

        /// <summary>
        /// 邀请码日志操作service
        /// </summary>
        private TInviteCodeLogService tInviteCodeLogService => new TInviteCodeLogService();

        #region 登录后相关操作

        /// <summary>
        /// 通过UPN获取登录用户相关信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("api/user/GetUserInfoByUPN")]
        public ServiceResponse<OperatorModel> GetUserInfoByUPN()
        {
            var userInfo = CurrentUserModel;
            return ServiceResponse<OperatorModel>.SuccessResponse("success", userInfo);
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("api/user/GetUserPermission")]
        public ServiceResponse<List<MenuViewModel>> GetUserPermission()
        {
            List<MenuViewModel> permission = new List<MenuViewModel>();
            Guid userId = CurrentUserModel?.UserId ?? Guid.Empty;
            var mlist = menuService.GetUserTreeMenusByUserId(userId);
            return ServiceResponse<List<MenuViewModel>>.SuccessResponse("success", mlist);
            //var lsmenu = menuService.GetUserMenusByLoginInfo(userId);
            //GetMenuViewModels(permission, lsmenu, Guid.Parse("00000000-0000-0000-0000-000000000000"));
            //var res = RecursionExtensions.MenuTree(permission, new Guid());
            //return ServiceResponse<List<MenuViewModel>>.SuccessResponse("success", res);
        }
        /// <summary>
        /// 递归菜单，为菜单添加所属系统类型
        /// </summary>
        /// <param name="viewModels"></param>
        /// <param name="models"></param>
        /// <param name="parentId"></param>
        private void GetMenuViewModels(List<MenuViewModel> viewModels, List<EMenu> models, Guid parentId)
        {
            var subList = models.Where(m => m.ParentId == parentId).OrderBy(m => m.Sort).ToList();
            foreach (var menu in subList)
            {
                var viewModel = new MenuViewModel
                {
                    Id = menu.Id,
                    Component = menu.Component,
                    Name = menu.Name,
                    Title = menu.Title,
                    Path = menu.Path,
                    Redirect = menu.Redirect,
                    Code = menu.Code,
                    Type = menu.Type,
                    Sort = menu.Sort,
                    Meta = new MetaModel
                    {
                        Title = menu.Title,
                        Icon = menu.Icon,
                        Roles = new List<string> { "admin" },
                        Affix = menu.Affix,
                        NoCache = menu.NoCache
                    },
                    Hidden = !menu.NoCache,
                    ParentId = parentId
                };
                if (menu.ParentId == Guid.Parse("00000000-0000-0000-0000-000000000000"))
                {
                    viewModel.PlatformType = menu.Code;
                }
                else
                {
                    viewModel.PlatformType = viewModels.FirstOrDefault(m => m.Id == parentId)?.PlatformType ?? "";
                }
                viewModels.Add(viewModel);
                GetMenuViewModels(viewModels, models, viewModel.Id);
            }
        }

        #endregion

        /// <summary>
        /// 角色菜单关联操作service
        /// </summary>
        protected RMenuURService RMenuURService = new RMenuURService();

        #region Base信息

        /// <summary>
        /// 获取所有用户信息-base
        /// </summary>
        /// <returns></returns>
        public List<ESysUser> GetAllUsers()
        {
            #region 组合Expression

            Expression<Func<ESysUser, bool>> explist = null;
            explist = u => u.IsDelete == false;

            #endregion

            return userService.FindList(explist, "CreateTime", true).ToList();
        }

        /// <summary>
        /// 获取用户基础信息-base
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Route("api/user/searchUserList")]
        [HttpPost]
        public object SearchUserList(ESysUser filter)
        {
            #region 组合Expression

            Expression<Func<ESysUser, bool>> explist = null;
            explist = u => u.IsDelete == false;

            explist = LinqExpression.And(explist, u => u.OrgCode == CurrentUserModel.OrgCode);
            if (!string.IsNullOrWhiteSpace(filter.UserType))
            {
                explist = LinqExpression.And(explist, u => u.UserType == filter.UserType);
            }
            if (!string.IsNullOrWhiteSpace(filter.UserName))
            {
                explist = LinqExpression.And(explist, u => u.UserName.Contains(filter.UserName));
            }
            if (!string.IsNullOrWhiteSpace(filter.LoginName))
            {
                explist = LinqExpression.And(explist, u => u.LoginName.Contains(filter.LoginName));
            }
            if (!string.IsNullOrWhiteSpace(filter.Unumber))
            {
                explist = LinqExpression.And(explist, u => u.Unumber.Contains(filter.Unumber));
            }
            if (filter.Sex != -1)
            {
                explist = LinqExpression.And(explist, u => u.Sex == filter.Sex);
            }
            if (filter.AccountStatus != -1)
            {
                explist = LinqExpression.And(explist, u => u.AccountStatus == filter.AccountStatus);
            }

            #endregion

            var myList = userService.FindList(explist, "CreateTime", true).ToList();
            return ServiceResponse<object>.SuccessResponse(myList);
        }

        /// <summary>
        /// 获取用户基础信息-base
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("api/user/searchUsers")]
        [HttpPost]
        public object SearchUsers(UserFilterViewModel request)
        {
            Expression<Func<ESysUser, bool>> whereLamdba = (u) => u.IsDelete == false;

            if (!string.IsNullOrEmpty(request.UserName))
                whereLamdba = whereLamdba.And(u => u.UserName.Contains(request.UserName));
            if (!string.IsNullOrEmpty(request.LoginName))
                whereLamdba = whereLamdba.And(u => u.LoginName.Contains(request.LoginName));
            if (!string.IsNullOrEmpty(request.MobilePhone))
                whereLamdba = whereLamdba.And(u => u.MobilePhone.Contains(request.MobilePhone));
            if (!string.IsNullOrEmpty(request.UserType))
                whereLamdba = whereLamdba.And(u => u.UserType.Equals(request.UserType));
            if (!string.IsNullOrWhiteSpace(request.Unumber))
                whereLamdba = LinqExpression.And(whereLamdba, u => u.Unumber.Contains(request.Unumber));
            if (request.Sex != -1)
                whereLamdba = LinqExpression.And(whereLamdba, u => u.Sex == request.Sex);
            if (request.AccountStatus != -1)
                whereLamdba = LinqExpression.And(whereLamdba, u => u.AccountStatus == request.AccountStatus);
            whereLamdba = LinqExpression.And(whereLamdba, u => u.OrgCode == CurrentUserModel.OrgCode);

            var items = userService.FindPageList(request.Page, request.PageSize, out var total, request.OrderBy, request.SortDir, whereLamdba).ToList();
            var page = new Page<ESysUser>
            {
                TotalItems = total,
                CurrentPage = request.Page,
                Items = items,
                ItemsPerPage = request.PageSize
            };

            return ServiceResponse<object>.SuccessResponse(page);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [Route("api/user/insertUserInfo")]
        [HttpPost]
        public object InsertUserInfo(ESysUser user)
        {
            user.UserID = GuidUtil.NewSequentialId();
            user.OrgCode = CurrentUserModel.OrgCode;
            user.CreateTime = DateTime.Now;
            user.ModifyTime = DateTime.Now;
            user.Password = user.Password;
            var myList = userService.Add(user);
            if (myList != null) return ServiceResponse<object>.SuccessResponse("添加用户成功");
            else return ServiceResponse<object>.ErrorResponse("添加用户失败");
        }

        /// <summary>
        /// 添加用户-批量
        /// </summary>
        /// <param name="users"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        [Route("api/user/insertUsers")]
        [HttpPost]
        public object InsertUsers(List<ESysUser> users, string userType)
        {
            var succe = new List<ESysUser>();
            var faile = new List<ESysUser>();
            ESysUser s = null;
            foreach (var u in users)
            {
                s = new ESysUser();
                s.AccountStatus = AccountStatusEnum.Enabled.IntValue();
                s.Birthday = u.Birthday;
                s.Creater = CurrentUserModel.LoginName;
                s.CreateTime = DateTime.Now;
                s.Email = u.Email;
                s.IsDelete = false;
                s.LoginName = u.Unumber;
                s.MobilePhone = u.MobilePhone;
                s.Modifyer = CurrentUserModel.LoginName;
                s.ModifyTime = DateTime.Now;
                s.OrgCode = CurrentUserModel.OrgCode;
                s.Password = CommonConst.UserDefaultPsw; //CurrentUserModel.OrgCode + "edu" + u.Unumber +"@";
                s.Remark = u.Remark;
                s.Sex = u.Sex;
                s.Unumber = u.Unumber;
                s.UserID = GuidUtil.NewSequentialId();
                s.UserName = u.UserName;
                s.UserType = userType;
                if (string.IsNullOrEmpty(s.Remark))
                    s.Remark = CommonConst.UserDefaultRemark;
                succe.Add(s);
            }

            var r = userService.Adds(succe);

            var list = new { succeed = succe, failed = faile };

            if (r == users.Count)
            {
                var json = new { list, msg = "添加用户成功" };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else if (r > 0)
            {
                var json = new { list, msg = ("添加用户成功" + r + "人" + "；失败" + (users.Count - r) + "人") };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else
            {
                var json = new { list, msg = "添加用户失败" };
                return ServiceResponse<object>.ErrorResponse("操作失败", json);
            }
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [Route("api/user/updateUserInfo")]
        [HttpPost]
        public object UpdateUserInfo(ESysUser user)
        {
            user.ModifyTime = DateTime.Now;
            //var aad = aadService.UpdateUser(user);
            //if (aad != UserStatusEunm.Success)
            //{
            //    return ServiceResponse<object>.ErrorResponse(aad.ToString());
            //}
            var myList = userService.Update(user);
            if (myList) return ServiceResponse<object>.SuccessResponse("更新用户信息成功");
            else return ServiceResponse<object>.ErrorResponse("更新用户信息失败");
        }

        /// <summary>
        /// 修改用户启用/禁用状态
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="Enabled"></param>
        /// <returns></returns>
        [HttpPost, Route("api/user/abledUser")]
        public object AbledUser(string UserID, bool Enabled)
        {
            var id = Guid.Parse(UserID);
            var user = userService.Find(u => !u.IsDelete && u.UserID == id);
            if (user == null) return ServiceResponse<object>.SuccessResponse("未找到用户");
            user.AccountStatus = Enabled ? 1 : 0;
            ;
            user.Modifyer = CurrentUserModel.LoginName;
            user.ModifyTime = DateTime.Now;
            var r = userService.Update(user);
            var str = Enabled ? "启用" : "禁用";
            ;
            if (r) return ServiceResponse<object>.SuccessResponse(str + "用户成功");
            else return ServiceResponse<object>.ErrorResponse(str + "用户失败");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        [Route("api/user/delUser")]
        [HttpPost]
        public object DeleteUser(String UserID)
        {
            var userID = Guid.Parse(UserID);

            #region 组合Expression

            Expression<Func<ESysUser, bool>> explist = null;
            explist = u => u.UserID == userID;

            #endregion

            var user = userService.Find(explist);
            user.IsDelete = true;
            user.AccountStatus = 0;
            var myList = userService.Update(user);
            if (myList) return ServiceResponse<object>.SuccessResponse("删除用户成功");
            else return ServiceResponse<object>.ErrorResponse("删除用户失败");
        }

        /// <summary>
        /// 根据用户名获取菜单列表
        /// </summary>
        /// <param name="LoginName"></param>
        /// <returns></returns>
        //[Route("api/user/getMenusByLoginName")]
        //[HttpGet]
        //public object GetMenusByLoginName(string LoginName)
        //{
        //    var myList = menuService.GetUserTreeMenusByUserId(LoginName);
        //    return ServiceResponse<object>.SuccessResponse(myList);
        //}

        #endregion

        #region yang

        /// <summary>
        /// 获取用户列表
        /// </summary>
        [HttpPost, Route("api/user/GetUserList")]
        [AllowAnonymous]
        public ServiceResponse<GetUserViewModel> GetUserList(GetUserRequest request)
        {
            //var orgCode = CurrentUserModel.OrgCode;
            //if (orgCode != CommonConst.DEFAULT_ORGCODE)//如果不是平台用户，则只能看到自己学校的用户列表
            //    request.OrgCode = orgCode;

            var viewModel = new GetUserViewModel();
            var userPage = userService.GetUserList(request);
            if (userPage != null)
            {
                viewModel.TotalCount = userPage.TotalItems.ObjToInt();
                var userIds = userPage.Items.Select(u => u.UserID);
                var ruList = RoleUserService.FindList(r => userIds.Contains(r.UserID)).ToList();

                foreach (var user in userPage.Items)
                {
                    var u = user.MapTo<GetUserItem, ESysUser>();
                    u.CreateTime = user.CreateTime.ToString("yyyy-MM-dd HH:mm");
                    u.ModifyTime = user.ModifyTime;
                    u.ConfirmPassword = u.Password = user.Password;
                    u.ShowHeadPhoto = PictureHelper.GetFileFullPath(u.HeadPhoto);
                    u.Sex = SexHelper.SexToStr(user.Sex);
                    var temp = ruList.Where(r => r.UserID == u.UserId).Select(r => r.RoleID).ToList();
                    u.RoleIdList.AddRange(temp);
                    viewModel.UserItems.Add(u);
                }
            }

            return ServiceResponse<GetUserViewModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 获取经销商和销售助手列表
        /// </summary>
        [HttpPost, Route("api/user/GetISVUserList")]
        public ServiceResponse<GetUserViewModel> GetISVUserList(GetUserRequest request)
        {
            var viewModel = new GetUserViewModel();
            var userPage = userService.GetISVUserList(request);
            if (userPage != null)
            {
                viewModel.TotalCount = userPage.TotalItems.ObjToInt();
                var userIds = userPage.Items.Select(u => u.UserID);
                var ruList = RoleUserService.FindList(r => userIds.Contains(r.UserID)).ToList();

                foreach (var user in userPage.Items)
                {
                    var u = user.MapTo<GetUserItem, SysUserModel>();
                    u.CreateTime = user.CreateTime.ToString("yyyy-MM-dd HH:mm");
                    u.ModifyTime = user.ModifyTime;
                    u.ConfirmPassword = u.Password = user.Password;
                    u.Sex = SexHelper.SexToStr(user.Sex);
                    var temp = ruList.Where(r => r.UserID == u.UserId).Select(r => r.RoleID).ToList();
                    u.RoleIdList.AddRange(temp);
                    viewModel.UserItems.Add(u);
                }
            }

            return ServiceResponse<GetUserViewModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        [HttpPost, Route("api/user/AddUser")]
        public ServiceResponse<GetUserItem> AddUser(GetUserItem userItem)
        {
            var user = new ESysUser
            {
                UserID = Guid.NewGuid(),
                AccountStatus = 1,
                Birthday = userItem.Birthday,
                CreateTime = DateTime.Now,
                Creater = CurrentUserModel.LoginName,
                Company = userItem.Company,
                Department = userItem.Department,
                Email = userItem.Email,
                HeadPhoto = userItem.HeadPhoto,
                IsDelete = false,
                ModifyTime = DateTime.Now,
                Position = userItem.Position,
                MobilePhone = userItem.MobilePhone,
                Remark = userItem.Remark,
                LoginName = userItem.LoginName,
                UserName = userItem.UserName,
                UserType = userItem.UserType,
                OfficeTel = userItem.OfficeTel,
                OrgCode = userItem.OrgCode ?? CommonConst.DEFAULT_ORGCODE,
                Password = userItem.Password,
                //Password = DESProvider.EncryptString(userItem.Password),
                Sex = SexHelper.SexToInt(userItem.Sex)
            };
            if (string.IsNullOrEmpty(user.HeadPhoto))
                user.HeadPhoto = CommonConst.UserDefaultHeadPhoto;
            if (string.IsNullOrEmpty(user.Remark))
                user.Remark = CommonConst.UserDefaultRemark;

            var temp = userService.FindList(t => !t.IsDelete && t.LoginName.Equals(user.LoginName));
            if (temp.Any())
                return ServiceResponse<GetUserItem>.SuccessResponse("用户登录名已存在，请重新输入", userItem, CommonConst.Code_OprateError);

            var inviteCode = GetInviteCode(user.OrgCode, user.UserID);

            user.InviteCode = inviteCode;
            var u = userService.Add(user);

            userItem.UserId = user.UserID;
            return ServiceResponse<GetUserItem>.SuccessResponse("success", userItem);
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        [HttpPost, Route("api/user/UpdateUser")]
        public ServiceResponse<GetUserItem> UpdateUser(GetUserItem userItem)
        {
            var user = userService.GetUserById(userItem.UserId);
            user.AccountStatus = 1;
            user.Birthday = userItem.Birthday;
            user.Company = userItem.Company;
            user.Department = userItem.Department;
            user.Email = userItem.Email;
            user.HeadPhoto = userItem.HeadPhoto;
            user.OrgCode = userItem.OrgCode ?? CommonConst.DEFAULT_ORGCODE;
            user.ModifyTime = DateTime.Now;
            user.Position = userItem.Position;
            user.MobilePhone = userItem.MobilePhone;
            user.Remark = userItem.Remark;
            user.UserName = userItem.UserName;
            user.OfficeTel = userItem.OfficeTel;
            //user.Password = DESProvider.EncryptString(userItem.Password);
            user.Sex = SexHelper.SexToInt(userItem.Sex);
            if (string.IsNullOrEmpty(user.HeadPhoto))
                user.HeadPhoto = CommonConst.UserDefaultHeadPhoto;
            if (string.IsNullOrEmpty(user.Remark))
                user.Remark = CommonConst.UserDefaultRemark;

            var temp = userService.FindList(t => !t.IsDelete && t.LoginName.Equals(user.LoginName) && user.UserID != t.UserID);
            if (temp.Any())
                return ServiceResponse<GetUserItem>.SuccessResponse("用户登录名已存在，请重新输入", userItem, CommonConst.Code_OprateError);

            var u = userService.Update(user);

            return ServiceResponse<GetUserItem>.SuccessResponse("success", userItem);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户id</param>
        [HttpPost, Route("api/user/DeleteUser")]
        public ServiceResponse<int> DeleteUser(Guid id)
        {
            var user = userService.Find(u => !u.IsDelete && u.UserID == id);
            user.IsDelete = true;
            user.AccountStatus = 0;
            var rus = RoleUserService.FindList(r => r.UserID == user.UserID).ToList();
            if (rus.Any())
                RoleUserService.DeletesNoSaveChange(rus);

            var b = userService.Update(user);
            return ServiceResponse<int>.SuccessResponse(1);
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        [HttpPost, Route("api/user/ResetPwd")]
        public ServiceResponse<bool> ResetPwd(ResetPwdRequest request)
        {
            if (string.IsNullOrEmpty(request.Password))
                return ServiceResponse<bool>.SuccessResponse("密码不能为空", false);

            var user = userService.Find(u => !u.IsDelete && u.UserID == request.UserId);
            user.ModifyTime = DateTime.Now;
            user.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
            user.Password = request.Password;

            var b = userService.Update(user);
            return ServiceResponse<bool>.SuccessResponse(b);
        }

        /// <summary>
        /// 分配角色
        /// </summary>
        [HttpPost, Route("api/user/HandleRole")]
        public ServiceResponse<GetUserItem> HandleRole(GetUserItem userItem)
        {
            //删除掉原来的关联
            var rs = RoleUserService.FindList(r => r.UserID == userItem.UserId).ToList();
            if (rs.Any())
                RoleUserService.Deletes(rs);

            //插入新的关联关系
            var urList = new List<RRoleUser>();
            foreach (var roleId in userItem.RoleIdList)
            {
                var urModel = new RRoleUser
                {
                    ID = GuidUtil.NewSequentialId(),
                    RoleID = roleId,
                    UserID = userItem.UserId
                };
                urList.Add(urModel);
            }
            RoleUserService.Adds(urList);
            return ServiceResponse<GetUserItem>.SuccessResponse("success", userItem);
        }

        /// <summary>
        /// 分配菜单权限
        /// </summary>
        [HttpPost, Route("api/user/HandleMenu")]
        public ServiceResponse<GetUserItem> HandleMenu(GetUserItem userItem)
        {
            //删除掉原来的关联
            var rs = RMenuURService.FindList(r => !r.IsDelete && r.KeyId == userItem.UserId).ToList();
            if (rs.Any())
                RMenuURService.Deletes(rs);

            //插入新的关联关系
            var urList = new List<RMenuUR>();
            foreach (var menuId in userItem.MenuIdList)
            {
                var urModel = new RMenuUR
                {
                    IsDelete = false,
                    IsUsed = true,
                    Id = GuidUtil.NewSequentialId(),
                    KeyId = userItem.UserId,
                    MenuId = menuId,
                    IsHalfChecked = false,
                    CreateTime = DateTime.Now
                };
                urList.Add(urModel);
            }
            foreach (var menuId in userItem.HalfMenuIdList)
            {
                var urModel = new RMenuUR
                {
                    IsDelete = false,
                    IsUsed = true,
                    Id = GuidUtil.NewSequentialId(),
                    KeyId = userItem.UserId,
                    MenuId = menuId,
                    IsHalfChecked = true,
                    CreateTime = DateTime.Now
                };
                urList.Add(urModel);
            }
            RMenuURService.Adds(urList);
            return ServiceResponse<GetUserItem>.SuccessResponse("success", userItem);
        }

        /// <summary>
        /// 用户名是否存在
        /// </summary>
        [HttpGet, Route("api/user/IsExistUser")]
        public ServiceResponse<bool> IsExistUser(Guid id, string loginName)
        {
            var user = userService.Find(u => !u.IsDelete && u.UserID != id && u.LoginName == loginName);
            var r = user == null;
            return ServiceResponse<bool>.SuccessResponse(r);
        }

        /// <summary>
        /// 获取注册用户列表
        /// </summary>
        [HttpPost, Route("api/user/GetRegesterList")]
        public ServiceResponse<GetUserViewModel> GetRegesterList(GetUserRequest request)
        {
            var viewModel = new GetUserViewModel();
            var userPage = userService.GetRegesterList(request);
            if (userPage != null)
            {
                viewModel.TotalCount = userPage.TotalItems.ObjToInt();
                var orgCodes = userPage.Items.Select(u => u.OrgCode).ToList();
                var orgs = orgService.FindList(o => orgCodes.Contains(o.org_code)).ToList();
                foreach (var user in userPage.Items)
                {
                    var u = new GetUserItem
                    {
                        UserId = user.UserID,
                        AccountStatus = user.AccountStatus,
                        Birthday = user.Birthday,
                        CreateTime = user.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                        Company = user.Company,
                        Creater = user.Creater,
                        Department = user.Department,
                        Email = user.Email,
                        HeadPhoto = user.HeadPhoto,
                        LoginName = user.LoginName,
                        ModifyTime = user.ModifyTime,
                        MobilePhone = user.MobilePhone,
                        Position = user.Position,
                        Remark = user.Remark,
                        UserName = user.UserName,
                        UserType = user.UserType,
                        OrgCode = user.OrgCode,
                        OrgName = orgs.FirstOrDefault(r => r.org_code == user.OrgCode)?.org_name ?? string.Empty,
                        OfficeTel = user.OfficeTel,
                        Password = user.Password,
                        ConfirmPassword = user.Password,
                        Sex = SexHelper.SexToStr(user.Sex)
                    };
                    viewModel.UserItems.Add(u);
                }
            }

            return ServiceResponse<GetUserViewModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 修改用户启用/禁用状态
        /// </summary>
        [HttpPost, Route("api/user/ChangeUserStatus")]
        public ServiceResponse<int> ChangeUserStatus(Guid id, bool status)
        {
            var user = userService.Find(u => !u.IsDelete && u.UserID == id);
            user.AccountStatus = status ? 1 : 0;
            ;
            var r = userService.Update(user);
            return ServiceResponse<int>.SuccessResponse(1);
        }

        /// <summary>
        /// 添加admin用户-批量
        /// </summary>
        [Route("api/user/InsertAdminUsersTest")]
        [HttpPost]
        public object InsertAdminUsersTest(List<InsertAdminUsersViewModel> users, string userType)
        {
            var succe = new List<ESysUser>();
            var faile = new List<ESysUser>();
            var names = userService.FindList(u => !u.IsDelete).Select(u => u.LoginName).ToList();
            foreach (var u in users)
            {
                var s = new ESysUser
                {
                    AccountStatus = AccountStatusEnum.Enabled.IntValue(),
                    Creater = CurrentUserModel.LoginName,
                    CreateTime = DateTime.Now,
                    Birthday = DateTime.ParseExact(u.出生日期, "yyyyMMdd", CultureInfo.CurrentCulture),
                    Email = string.Empty,
                    IsDelete = false,
                    LoginName = GetLoginName(u.职员名称),
                    MobilePhone = string.Empty,
                    Modifyer = CurrentUserModel.LoginName,
                    ModifyTime = DateTime.ParseExact(u.更新时间, "yyyyMMddHHmmssfff", CultureInfo.CurrentCulture),
                    OrgCode = CommonConst.UserDefaultOrgCode,
                    Password = CommonConst.UserDefaultPsw,
                    Remark = CommonConst.UserDefaultRemark,
                    Sex = SexHelper.SexToInt(u.性别),
                    UserID = GuidUtil.NewSequentialId(),
                    UserName = u.职员名称,
                    UserType = userType,
                    Unumber = u.职员代码,
                    CardNo = u.身份证号,
                    Company = string.Empty,
                    Department = string.Empty,
                    HeadPhoto = CommonConst.UserDefaultHeadPhoto,
                    OfficeTel = string.Empty,
                    Position = string.Empty
                };
                if (!string.IsNullOrEmpty(s.CardNo) && s.CardNo.Length > 14)
                {
                    var str = s.CardNo.Substring(6, 8);
                    try
                    {
                        s.Birthday = DateTime.ParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
                var t = names.Where(f => f == s.LoginName);
                var p1 = succe.Where(o => o.LoginName == s.LoginName);
                if (t.Any() || p1.Any())
                {
                    s.Remark = "登录名重复";
                    faile.Add(s);
                }
                else
                {
                    succe.Add(s);
                }
            }

            var r = userService.Adds(succe);

            var list = new { succeed = succe, failed = faile };

            if (r == users.Count)
            {
                var json = new { list, msg = "添加用户成功" };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else if (r > 0)
            {
                var json = new { list, msg = ("添加用户成功" + r + "人；失败" + (users.Count - r) + "人，登录名重复") };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else
            {
                var json = new { list, msg = "添加用户失败" };
                return ServiceResponse<object>.SuccessResponse(CommonConst.OprateFailStr, json);
            }
        }

        /// <summary>
        /// 根据姓名获取对应的登录名
        /// </summary>
        private string GetLoginName(string userName)
        {
            var fullSpell = PinYinHelper.ConvertToAllSpell(userName); //全拼
            return fullSpell;
        }

        /// <summary>
        /// 导入销售助手用户
        /// </summary>
        [HttpPost, Route("api/user/InsertAdminUsers")]
        [AllowAnonymous]
        public object InsertAdminUsers()
        {
            var result = CommonConst.UploadFailDefaultUrl;
            var filelist = HttpContext.Current.Request.Files;
            var users = new List<InsertAdminUsersViewModel>();
            if (filelist.Count > 0)
            {
                for (var i = 0; i < filelist.Count; i++)
                {
                    var file = filelist[i];
                    var fileName = file.FileName;
                    var fn = fileName.Split('\\');
                    if (fn.Length > 1)
                    {
                        fileName = fn[fn.Length - 1];
                    }
                    DataTable dataTable = null;
                    var fs = fileName.Split('.');
                    if (fs.Length > 1)
                    {
                        var ext = fs[fs.Length - 1];
                        if (ext == "xlsx")
                            dataTable = ExcelHelp.ExcelToTableForXLSX(file.InputStream); //excel转成datatable
                        else
                            dataTable = ExcelHelp.ExcelToTableForXLS(file.InputStream); //excel转成datatable
                    }
                    users = dataTable.ToDataList<InsertAdminUsersViewModel>(); //datatable转成list
                }
            }
            var succe = new List<ESysUser>();
            var faile = new List<ESysUser>();
            var exportList = new List<InsertAdminUsersViewModel>();
            var allUsers = userService.FindList(u => !u.IsDelete).ToList();
            //数据list转成数据库实体对应的list
            foreach (var u in users)
            {
                var s = new ESysUser
                {
                    AccountStatus = AccountStatusEnum.Enabled.IntValue(),
                    Creater = CurrentUserModel?.LoginName ?? string.Empty,
                    CreateTime = DateTime.Now,
                    //Birthday = DateTime.ParseExact(u.出生日期, "yyyyMMdd", CultureInfo.CurrentCulture),
                    Email = string.Empty,
                    IsDelete = false,
                    LoginName = u.职员名称,
                    MobilePhone = string.Empty,
                    Modifyer = CurrentUserModel?.LoginName ?? string.Empty,
                    ModifyTime = DateTime.ParseExact(u.更新时间, "yyyyMMddHHmmssfff", CultureInfo.CurrentCulture),
                    OrgCode = CommonConst.UserDefaultOrgCode,
                    Password = CommonConst.UserDefaultPsw,
                    Remark = CommonConst.UserDefaultRemark,
                    Sex = SexHelper.SexToInt(u.性别),
                    UserID = GuidUtil.NewSequentialId(),
                    UserName = u.职员名称,
                    UserType = UserType.UserTypeSTUDENT,
                    Unumber = u.职员代码,
                    CardNo = u.身份证号,
                    Company = string.Empty,
                    Department = string.Empty,
                    HeadPhoto = CommonConst.UserDefaultHeadPhoto,
                    OfficeTel = string.Empty,
                    Position = string.Empty
                };

                if (string.IsNullOrEmpty(u.经销商号) || string.IsNullOrEmpty(u.职员代码) || string.IsNullOrEmpty(u.职员名称))
                {
                    s.Remark = "经销商号/职员代码/职员名称必填";
                    faile.Add(s);
                    u.原因 = s.Remark;
                    exportList.Add(u);
                    continue;
                }

                try
                {
                    s.Birthday = DateTime.ParseExact(u.出生日期, "yyyyMMdd", CultureInfo.CurrentCulture);
                }
                catch (Exception e)
                {
                    s.Birthday = DateTime.MinValue;
                }

                var t = allUsers.Where(f => f.Unumber == s.Unumber && f.UserType == UserType.UserTypeSTUDENT);
                var p1 = succe.Where(o => o.Unumber == s.Unumber && s.UserType == UserType.UserTypeSTUDENT);
                if (t.Any() || p1.Any())
                {
                    s.Remark = "Unumber/AgentNumber重复";
                    faile.Add(s);
                    u.原因 = s.Remark;
                    exportList.Add(u);
                }
                else
                {
                    succe.Add(s);
                }
            }
            var dt = succe.ToDataTable(null);
            if (string.IsNullOrEmpty(dt.TableName))
                dt.TableName = "ESysUser";
            var r = succe.Count;
            SqlBulkCopyHelper.SaveTable(dt);


            var extDt = exportList.ToDataTable(null);
            var fileFullPath = GetPath();
            ExcelHelp.TableToExcelForXLSX(extDt, fileFullPath);
            var url = SaveFile("平台用户失败信息.xlsx", fileFullPath);

            var list = new { failed = faile.Take(100).ToList(), failedCount = faile.Count }; //数据太多的话，浏览器会崩溃

            if (r == users.Count)
            {
                var json = new { list, msg = "添加用户成功", url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else if (r > 0)
            {
                var json = new { list, msg = ("添加用户成功" + r + "人；失败" + (users.Count - r) + "人，登录名重复"), url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else
            {
                var json = new { list, msg = "添加用户失败", url };
                return ServiceResponse<object>.SuccessResponse(CommonConst.OprateFailStr, json);
            }
        }

        /// <summary>
        /// 导入平台用户
        /// </summary>
        [HttpPost, Route("api/user/InsertSGMWAdminUsers")]
        //[AllowAnonymous]
        public object InsertSGMWAdminUsers(string userType)
        {
            var result = CommonConst.UploadFailDefaultUrl;
            var filelist = HttpContext.Current.Request.Files;
            var users = new List<ESysUser>();
            var path = HttpContext.Current.Server.MapPath("/ImportConfig/sgmwConfig.xml");
            var xr = XMLHelper.ReadToHashtable(path);
            if (filelist.Count > 0)
            {
                for (var i = 0; i < filelist.Count; i++)
                {
                    var file = filelist[i];
                    var fileName = file.FileName;
                    var fn = fileName.Split('\\');
                    if (fn.Length > 1)
                    {
                        fileName = fn[fn.Length - 1];
                    }
                    DataTable dataTable = null;
                    var fs = fileName.Split('.');
                    if (fs.Length > 1)
                    {
                        var ext = fs[fs.Length - 1];
                        if (ext == "xlsx")
                            dataTable = ExcelHelp.ExcelToTableForXLSX(file.InputStream, xr.ImportHashtable); //excel转成datatable
                        else
                            dataTable = ExcelHelp.ExcelToTableForXLS(file.InputStream); //excel转成datatable
                    }
                    //users = dataTable.ToDataList<InsertSGMWAdminUsersViewModel>(); //datatable转成list
                    users = dataTable.ToDataList<ESysUser>(); //datatable转成list
                }
            }
            var succe = new List<ESysUser>();
            var faile = new List<ESysUser>();
            var exportList = new List<ESysUser>();
            var names = userService.FindList(u => !u.IsDelete).Select(u => u.LoginName).ToList();
            //数据list转成数据库实体对应的list
            foreach (var u in users)
            {
                u.UserID = GuidUtil.NewSequentialId();
                u.UserType = userType;
                u.OrgCode = CurrentUserModel.OrgCode ?? CommonConst.UserDefaultOrgCode;
                u.Password = CommonConst.UserDefaultPsw;
                u.HeadPhoto = CommonConst.UserDefaultHeadPhoto;
                u.AccountStatus = 1;
                u.CreateTime = DateTime.Now;
                u.ModifyTime = DateTime.Now;
                u.Creater = CurrentUserModel.LoginName ?? string.Empty;
                u.Modifyer = CurrentUserModel.LoginName ?? string.Empty;
                if (string.IsNullOrEmpty(u.LoginName) || string.IsNullOrEmpty(u.MobilePhone) || string.IsNullOrEmpty(u.UserName))
                {
                    u.Remark = "登录名/姓名/移动电话必填";
                    faile.Add(u);
                    exportList.Add(u);
                    continue;
                }

                var t = names.Where(f => f == u.LoginName);
                var p1 = succe.Where(o => o.LoginName == u.LoginName);
                if (t.Any() || p1.Any())
                {
                    u.Remark = "登录名重复";
                    exportList.Add(u);
                    faile.Add(u);
                }
                else
                {
                    succe.Add(u);
                }
            }
            var dt = succe.ToDataTable(null);
            dt.TableName = "ESysUser";
            var r = succe.Count;
            SqlBulkCopyHelper.SaveTable(dt);

            var url = string.Empty;
            if (exportList.Any())
            {
                var extDt = exportList.ToDataTable(xr.ExportHashtable);
                var str = GetSavePath();
                var strs = str.Split(',');
                if (strs.Any() && strs.Length > 1)
                {
                    var fileFullPath = strs[0];
                    url = strs[1];
                    ExcelHelp.TableToExcelForXLSX(extDt, fileFullPath);
                }
            }

            var list = new { failed = faile.Take(100).ToList(), failedCount = faile.Count }; //数据太多的话，浏览器会崩溃

            if (r == users.Count)
            {
                var json = new { list, msg = "添加用户成功", url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else if (r > 0)
            {
                var json = new { list, msg = ("添加用户成功" + r + "人；失败" + (users.Count - r) + "人"), url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else
            {
                var json = new { list, msg = "添加用户失败", url };
                return ServiceResponse<object>.SuccessResponse(CommonConst.OprateFailStr, json);
            }
        }

        /// <summary>
        /// 获取文件保存路径
        /// </summary>
        private string GetPath()
        {
            var str = string.Empty;
            var virtualPath = "/UploadFile/Files/";
            var path = HttpContext.Current.Server.MapPath(virtualPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var fileFullPath = $"{path}{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            return fileFullPath;
        }

        private string GetSavePath()
        {
            var virtualPath = "/UploadFile/Files/ImportFail/";
            var path = HttpContext.Current.Server.MapPath(virtualPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var fn = $"失败信息{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileFullPath = $"{path}{fn}";
            return $"{fileFullPath},{fn}";
        }

        /// <summary>
        /// 文件上传到blob
        /// </summary>
        private string SaveFile(string fileName, string fileFullPath)
        {
            var fs = new FileStream(fileFullPath, FileMode.Open);
            var str = "#";
            //var bc = new BlobController();
            //var blobName = BlobHelper.GetBlobName(fileName);
            //var blobResult = bc.CreateBlod(blobName);
            //if (blobResult == ApiResultEunm.Success || blobResult == ApiResultEunm.Exist)
            //{
            //    //创建文件
            //    var apiResult = bc.UploadFileByStream(fs, fileName);
            //    if (apiResult.apiResultEunm == ApiResultEunm.Success && !string.IsNullOrEmpty(apiResult.info))
            //    {
            //        str = apiResult.info;
            //    }
            //}
            //fs.Dispose();
            //File.Delete(fileFullPath);
            return str;
        }

        /// <summary>
        /// 导入骏客用户
        /// </summary>
        [HttpPost, Route("api/user/InsertJKAdminUsers")]
        [AllowAnonymous]
        public object InsertJKAdminUsers()
        {
            var filelist = HttpContext.Current.Request.Files;
            var users = new List<ESysUser>();
            var path = HttpContext.Current.Server.MapPath("/ImportConfig/jkConfig.xml");
            var xr = XMLHelper.ReadToHashtable(path);

            if (filelist.Count > 0)
            {
                for (var i = 0; i < filelist.Count; i++)
                {
                    var file = filelist[i];
                    var fileName = file.FileName;
                    var fn = fileName.Split('\\');
                    if (fn.Length > 1)
                    {
                        fileName = fn[fn.Length - 1];
                    }
                    DataTable dataTable = null;
                    var fs = fileName.Split('.');
                    if (fs.Length > 1)
                    {
                        var ext = fs[fs.Length - 1];
                        dataTable = ExcelHelp.ExcelToTableForXLSX(file.InputStream, xr.ImportHashtable); //excel转成datatable
                    }
                    users = dataTable.ToDataList<ESysUser>(); //datatable转成list
                }
            }
            var succe = new List<ESysUser>();
            var faile = new List<ESysUser>();
            var exportList = new List<ESysUser>();
            //唯一标识 loginName+agentNumber
            var names = userService.FindList(u => !u.IsDelete).Select(u => new { u.LoginName, u.UserType }).ToList();
            //数据list转成数据库实体对应的list
            foreach (var u in users)
            {
                u.UserID = GuidUtil.NewSequentialId();
                u.UserType = UserType.UserTypeSTUDENT;
                u.OrgCode = CommonConst.UserDefaultOrgCode;
                u.Password = CommonConst.UserDefaultPsw;
                u.AccountStatus = 1;
                u.HeadPhoto = CommonConst.UserDefaultHeadPhoto;
                u.CreateTime = DateTime.Now;
                u.ModifyTime = DateTime.Now;
                u.Creater = CurrentUserModel?.LoginName ?? string.Empty;
                u.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;

                if (string.IsNullOrEmpty(u.LoginName) || string.IsNullOrEmpty(u.Unumber) || string.IsNullOrEmpty(u.UserName))
                {
                    u.Remark = "LoginName/AgentNumber/Unumber/UserName必填";
                    exportList.Add(u);
                    faile.Add(u);
                    continue;
                }

                var t = names.Where(f => f.LoginName == u.LoginName && f.UserType == UserType.UserTypeSTUDENT);
                var p1 = succe.Where(f => f.LoginName == u.LoginName && f.UserType == UserType.UserTypeSTUDENT);
                if (t.Any() || p1.Any())
                {
                    u.Remark = "LoginName/AgentNumber重复";
                    exportList.Add(u);
                    faile.Add(u);
                }
                else
                {
                    succe.Add(u);
                }
            }
            var dt = succe.ToDataTable(null);
            dt.TableName = "ESysUser";
            var r = succe.Count;
            SqlBulkCopyHelper.SaveTable(dt);

            var extDt = exportList.ToDataTable(xr.ExportHashtable);
            var fileFullPath = GetPath();
            ExcelHelp.TableToExcelForXLSX(extDt, fileFullPath);
            var url = SaveFile("骏客用户失败信息.xlsx", fileFullPath);

            var list = new { failed = faile.Take(100).ToList(), failedCount = faile.Count }; //数据太多的话，浏览器会崩溃

            if (r == users.Count)
            {
                var json = new { list, msg = "添加用户成功", url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else if (r > 0)
            {
                var json = new { list, msg = ("添加用户成功" + r + "人；失败" + (users.Count - r) + "人，登录名重复"), url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else
            {
                var json = new { list, msg = "添加用户失败", url };
                return ServiceResponse<object>.SuccessResponse(CommonConst.OprateFailStr, json);
            }
        }

        /// <summary>
        /// 导入教学平台用户
        /// </summary>
        [HttpPost, Route("api/user/InsertISVAdminUsers")]
        [AllowAnonymous]
        public object InsertISVAdminUsers()
        {
            var filelist = HttpContext.Current.Request.Files;
            var users = new List<ESysUser>();
            var path = HttpContext.Current.Server.MapPath("/ImportConfig/isvConfig.xml");
            var xr = XMLHelper.ReadToHashtable(path);
            if (filelist.Count > 0)
            {
                for (var i = 0; i < filelist.Count; i++)
                {
                    var file = filelist[i];
                    var fileName = file.FileName;
                    var fn = fileName.Split('\\');
                    if (fn.Length > 1)
                    {
                        fileName = fn[fn.Length - 1];
                    }
                    DataTable dataTable = null;
                    var fs = fileName.Split('.');
                    if (fs.Length > 1)
                    {
                        var ext = fs[fs.Length - 1];
                        if (ext == "xlsx")
                            dataTable = ExcelHelp.ExcelToTableForXLSX(file.InputStream, xr.ImportHashtable); //excel转成datatable
                        else
                            dataTable = ExcelHelp.ExcelToTableForXLS(file.InputStream); //excel转成datatable
                    }
                    users = dataTable.ToDataList<ESysUser>(); //datatable转成list
                }
            }
            var succe = new List<ESysUser>();
            var faile = new List<ESysUser>();
            var exportList = new List<ESysUser>();
            var names = userService.FindList(u => !u.IsDelete).Select(u => u.LoginName).ToList();
            //数据list转成数据库实体对应的list
            foreach (var u in users)
            {
                u.UserID = GuidUtil.NewSequentialId();
                u.UserType = UserType.UserTypeTEACHER;
                u.OrgCode = CommonConst.UserDefaultOrgCode;
                u.Password = CommonConst.UserDefaultPsw;
                u.HeadPhoto = CommonConst.UserDefaultHeadPhoto;
                u.AccountStatus = 1;
                u.CreateTime = DateTime.Now;
                u.ModifyTime = DateTime.Now;
                u.Creater = CurrentUserModel?.LoginName ?? string.Empty;
                u.Modifyer = CurrentUserModel?.LoginName ?? string.Empty;
                if (string.IsNullOrEmpty(u.LoginName) || string.IsNullOrEmpty(u.MobilePhone) || string.IsNullOrEmpty(u.UserName))
                {
                    u.Remark = "登录名/姓名/移动电话必填";
                    faile.Add(u);
                    exportList.Add(u);
                    continue;
                }

                var t = names.Where(f => f == u.LoginName);
                var p1 = succe.Where(o => o.LoginName == u.LoginName);
                if (t.Any() || p1.Any())
                {
                    u.Remark = "登录名重复";
                    exportList.Add(u);
                    faile.Add(u);
                }
                else
                {
                    succe.Add(u);
                }
            }
            var dt = succe.ToDataTable(null);
            dt.TableName = "ESysUser";
            var r = succe.Count;
            SqlBulkCopyHelper.SaveTable(dt);

            var extDt = exportList.ToDataTable(xr.ExportHashtable);
            var fileFullPath = GetPath();
            ExcelHelp.TableToExcelForXLSX(extDt, fileFullPath);
            var url = SaveFile("平台用户失败信息.xlsx", fileFullPath);

            var list = new { failed = faile.Take(100).ToList(), failedCount = faile.Count }; //数据太多的话，浏览器会崩溃

            if (r == users.Count)
            {
                var json = new { list, msg = "添加用户成功", url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else if (r > 0)
            {
                var json = new { list, msg = ("添加用户成功" + r + "人；失败" + (users.Count - r) + "人，登录名重复"), url };
                return ServiceResponse<object>.SuccessResponse(json);
            }
            else
            {
                var json = new { list, msg = "添加用户失败", url };
                return ServiceResponse<object>.SuccessResponse(CommonConst.OprateFailStr, json);
            }
        }

        #endregion

        /// <summary>
        /// 获取全部的教师列表
        /// </summary>
        [HttpGet, Route("api/user/GetAllTeacherList")]
        public ServiceResponse<List<GetUserItem>> GetAllTeacherList()
        {
            var viewModels = new List<GetUserItem>();
            var modelList = userService.FindList(u => !u.IsDelete && u.UserType == UserType.UserTypeTEACHER).ToList();
            if (modelList.Any())
            {
                var orgCodes = modelList.Select(u => u.OrgCode).ToList();
                var orgs = orgService.FindList(o => orgCodes.Contains(o.org_code)).ToList();
                foreach (var user in modelList)
                {
                    var u = new GetUserItem
                    {
                        UserId = user.UserID,
                        AccountStatus = user.AccountStatus,
                        Birthday = user.Birthday,
                        CreateTime = user.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                        Company = user.Company,
                        Creater = user.Creater,
                        Department = user.Department,
                        Email = user.Email,
                        HeadPhoto = user.HeadPhoto,
                        LoginName = user.LoginName,
                        ModifyTime = user.ModifyTime,
                        MobilePhone = user.MobilePhone,
                        Position = user.Position,
                        Remark = user.Remark,
                        UserName = user.UserName,
                        UserType = user.UserType,
                        OrgCode = user.OrgCode,
                        OrgName = orgs.FirstOrDefault(r => r.org_code == user.OrgCode)?.org_name ?? string.Empty,
                        OfficeTel = user.OfficeTel,
                        Password = user.Password,
                        ConfirmPassword = user.Password,
                        Sex = SexHelper.SexToStr(user.Sex)
                    };
                    viewModels.Add(u);
                }
            }

            return ServiceResponse<List<GetUserItem>>.SuccessResponse(viewModels);
        }

        /// <summary>
        /// 获取用户菜单-路由
        /// </summary>
        [HttpGet, Route("api/user/getRouter")]
        public object GetRouter()
        {
            var routersbase = new List<RouterViewModel>();
            var routerbase = new RouterViewModel();
            routerbase.path = "/redirect/:path*";
            routerbase.component = "@/views/redirect/index";
            routersbase.Add(routerbase);

            var routersbase1 = new List<RouterViewModel>();
            var meta = new Meta();
            meta.title = "";
            meta.icon = "";
            meta.noCache = true;
            meta.affix = true;
            var routerbase1 = new RouterViewModel();
            routerbase1.path = "dashboard";
            routerbase1.name = "dashboard";
            routerbase1.meta = meta;
            routerbase1.component = "@/views/dashboard/index";
            routersbase1.Add(routerbase1);


            var routers = new List<RouterViewModel>();

            var router = new RouterViewModel();
            router.path = "/redirect";
            router.component = "Layout";
            router.hidden = true;
            router.children = routersbase;
            routers.Add(router);


            var router1 = new RouterViewModel();
            router1.path = "/";
            router1.component = "Layout";
            router1.redirect = "/dashboard";
            router1.children = routersbase1;
            routers.Add(router1);


            return ServiceResponse<object>.SuccessResponse(routers);
        }
        
        /// <summary>
        /// 教学中心创建课程-导师列表
        /// </summary>
        [HttpGet, Route("api/user/GetTeacherList")]
        public ServiceResponse<List<TeacherListViewModel>> GetTeacherList()
        {
            var viewModels = new List<TeacherListViewModel>();
            var modelList = userService.FindList(u => !u.IsDelete && u.UserType == UserType.UserTypeTEACHER).OrderByDescending(w => w.CreateTime).ToList();
            if (modelList.Any())
            {
                foreach (var user in modelList)
                {
                    var u = new TeacherListViewModel
                    {
                        UserId = user.UserID,
                        Birthday = user.Birthday,
                        CreateTime = user.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                        Company = user.Company,
                        Creater = user.Creater,
                        Department = user.Department,
                        Email = user.Email,
                        HeadPhoto = user.HeadPhoto,
                        MobilePhone = user.MobilePhone,
                        Position = user.Position,
                        Remark = user.Remark,
                        UserName = user.UserName,
                        UserType = user.UserType,
                        OfficeTel = user.OfficeTel,
                        Sex = SexHelper.SexToStr(user.Sex)
                    };
                    viewModels.Add(u);
                }
            }

            return ServiceResponse<List<TeacherListViewModel>>.SuccessResponse(viewModels);
        }

        #region 销售助手-用户信息更新
        /// <summary>
        /// 新增用户-销售助手
        /// </summary>
        /// <param name="userxszs">销售助手用户实体</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("api/user/addUserxszs")]
        public ServiceResponse<bool> AddUserxszs(Userxszs userxszs)
        {
            if (userxszs == null) return ServiceResponse<bool>.SuccessResponse("用户信息不可为空", false);
            if (string.IsNullOrEmpty(userxszs.AgentNumber) || string.IsNullOrEmpty(userxszs.Unumber) || string.IsNullOrEmpty(userxszs.UserName)) return ServiceResponse<bool>.SuccessResponse("经销商号/职员代码/职员名称 不可为空", false);
            var exist = userService.Find(x => x.Unumber == userxszs.Unumber);
            if (exist != null) return ServiceResponse<bool>.SuccessResponse("用户已存在(经销商号码+职员编码 重复)", false);

            var s = new ESysUser
            {
                AccountStatus = AccountStatusEnum.Enabled.IntValue(),
                Creater = "第三方-销售助手",
                CreateTime = DateTime.Now,
                Modifyer = "第三方-销售助手",
                ModifyTime = DateTime.Now,
                Email = string.Empty,
                IsDelete = false,
                LoginName = userxszs.UserName,
                MobilePhone = string.Empty,
                OrgCode = CommonConst.UserDefaultOrgCode,
                Password = CommonConst.UserDefaultPsw,
                Remark = CommonConst.UserDefaultRemark,
                Sex = userxszs.Sex,
                Birthday = userxszs.Birthday,
                UserID = GuidUtil.NewSequentialId(),
                UserName = userxszs.UserName,
                UserType = UserType.UserTypeSTUDENT,
                Unumber = userxszs.Unumber,
                CardNo = userxszs.CardNo,
                Company = string.Empty,
                Department = string.Empty,
                HeadPhoto = CommonConst.UserDefaultHeadPhoto,
                OfficeTel = string.Empty,
                Position = string.Empty
            };
            var res = userService.Add(s);
            if (res == null) return ServiceResponse<bool>.SuccessResponse("用户新增失败，系统错误", false);
            return ServiceResponse<bool>.SuccessResponse("用户新增成功", true);
        }

        /// <summary>
        /// 更新用户-销售助手
        /// </summary>
        /// <param name="userxszs">销售助手用户实体</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("api/user/updateUserxszs")]
        public ServiceResponse<bool> UpdateUserxszs(Userxszs userxszs)
        {
            if (userxszs == null) return ServiceResponse<bool>.SuccessResponse("用户信息不可为空", false);
            if (string.IsNullOrEmpty(userxszs.AgentNumber) || string.IsNullOrEmpty(userxszs.Unumber) || string.IsNullOrEmpty(userxszs.UserName)) return ServiceResponse<bool>.SuccessResponse("经销商号/职员代码/职员名称 不可为空", false);
            var exist = userService.Find(x => x.Unumber == userxszs.Unumber);
            if (exist == null) return ServiceResponse<bool>.SuccessResponse("用户不存在(职员编码 查询没有记录)", false);

            exist.ModifyTime = DateTime.Now;
            exist.LoginName = userxszs.UserName;
            exist.Sex = userxszs.Sex;
            exist.Birthday = userxszs.Birthday;
            exist.UserName = userxszs.UserName;
            exist.CardNo = userxszs.CardNo;

            var res = userService.Update(exist);
            if (!res) return ServiceResponse<bool>.SuccessResponse("用户更新失败，系统错误", false);
            return ServiceResponse<bool>.SuccessResponse("用户更新成功", true);
        }

        /// <summary>
        /// 禁用/启用 用户-销售助手
        /// </summary>
        /// <param name="agentNumber">经销商号</param>
        /// <param name="unumber">职员代码</param>
        /// <param name="flag">禁用/启用：true-启用；false-禁用</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("api/user/ableUserxszs")]
        public ServiceResponse<bool> AbleUserxszs(string agentNumber, string unumber, bool flag)
        {
            if (string.IsNullOrEmpty(agentNumber) || string.IsNullOrEmpty(unumber)) return ServiceResponse<bool>.SuccessResponse("经销商号/职员代码 不可为空", false);
            var exist = userService.Find(x => x.Unumber == unumber);
            if (exist == null) return ServiceResponse<bool>.SuccessResponse("用户不存在(经销商号码+职员编码 查询没有记录)", false);

            exist.AccountStatus = flag ? 1 : 0;

            var res = userService.Update(exist);
            if (!res) return ServiceResponse<bool>.SuccessResponse("操作失败，系统错误", false);
            return ServiceResponse<bool>.SuccessResponse("操作成功", true);
        }

        /// <summary>
        /// 删除用户-销售助手
        /// </summary>
        /// <param name="agentNumber">经销商号</param>
        /// <param name="unumber">职员代码</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("api/user/deleteUserxszs")]
        public ServiceResponse<bool> DeleteUserxszs(string agentNumber, string unumber)
        {
            if (string.IsNullOrEmpty(agentNumber) || string.IsNullOrEmpty(unumber)) return ServiceResponse<bool>.SuccessResponse("经销商号/职员代码 不可为空", false);
            var exist = userService.Find(x => x.Unumber == unumber);
            if (exist == null) return ServiceResponse<bool>.SuccessResponse("用户不存在(经销商号码+职员编码 查询没有记录)", false);

            exist.IsDelete = true;

            var res = userService.Update(exist);
            if (!res) return ServiceResponse<bool>.SuccessResponse("用户删除失败，系统错误", false);
            return ServiceResponse<bool>.SuccessResponse("用户删除成功", true);
        }
        #endregion

        #region 骏客APP-用户信息更新
        /// <summary>
        /// 新增用户-骏客APP
        /// </summary>
        /// <param name="userjk">骏客APP用户实体</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("api/user/addUserjk")]
        public ServiceResponse<bool> AddUserjk(Userjk userjk)
        {
            EApplicationLog log = new EApplicationLog
            {
                AppUser = "WebAPI",
                LogDate = DateTime.Now,
                LogLevel = "Info",
                AspnetMVCController = "addUserjk",
                AspnetMVCAction = "syncUserJk",
                ExceptionMessage = userjk.UserName + "," + userjk.LoginName + "," + userjk.Unumber + "," + userjk.AgentNumber + ";",
                Message = "成功",
            };

            try
            {
                if (userjk.IsNull())
                {
                    log.LogLevel = "Fail";
                    log.Message = "用户信息为空";
                    logService.Add(log);
                    return ServiceResponse<bool>.SuccessResponse("用户信息不可为空", false);
                }
                if (string.IsNullOrEmpty(userjk.LoginName) || string.IsNullOrEmpty(userjk.AgentNumber) || string.IsNullOrEmpty(userjk.Unumber) || string.IsNullOrEmpty(userjk.UserName))
                {
                    log.LogLevel = "Fail";
                    log.Message = "登录账号/经销商号/职员代码/职员名称 为空";
                    logService.Add(log);
                    return ServiceResponse<bool>.SuccessResponse("登录账号/经销商号/职员代码/职员名称 不可为空", false);
                }
                ESysUser sysUser = new ESysUser
                {
                    AccountStatus = AccountStatusEnum.Enabled.IntValue(),
                    Creater = "第三方-骏客APP",
                    CreateTime = DateTime.Now,
                    Modifyer = "第三方-骏客APP",
                    ModifyTime = DateTime.Now,
                    Email = string.Empty,
                    IsDelete = false,
                    LoginName = userjk.LoginName,
                    MobilePhone = string.Empty,
                    OrgCode = CommonConst.UserDefaultOrgCode,
                    Password = CommonConst.UserDefaultPsw,
                    Remark = CommonConst.UserDefaultRemark,
                    Sex = userjk.Sex,
                    UserID = GuidUtil.NewSequentialId(),
                    UserName = userjk.UserName,
                    UserType = UserType.UserTypeSTUDENT,
                    Unumber = userjk.Unumber,
                    CardNo = userjk.CardNo,
                    Company = string.Empty,
                    Department = string.Empty,
                    HeadPhoto = CommonConst.UserDefaultHeadPhoto,
                    OfficeTel = string.Empty,
                    Position = string.Empty
                };

                var exist = userService.Find(x => x.LoginName == userjk.LoginName && x.UserType == UserType.UserTypeSTUDENT);
                // if (exist.IsNotNull()) return ServiceResponse<bool>.SuccessResponse("用户已存在(登录账号+经销商号码 重复)", false);
                if (exist.IsNotNull())
                {
                    log.AspnetMVCAction = "UpdateUserJk";

                    sysUser.AccountStatus = userjk.AccountStatus;
                    sysUser.UserID = GuidUtil.NewSequentialId();
                    userService.Update(sysUser);

                    log.Message = "更新用户成功";
                }
                else
                {
                    log.AspnetMVCAction = "AddUserJk";

                    userService.Add(sysUser);

                    log.Message = "新增用户成功";
                }

                logService.Add(log);
                // 为同步的用户添加默认角色，如果默认角色不存在，就不添加了
                var role = roleService.Find(x => !x.IsDelete && x.RoleName == "骏客");
                if (role.IsNull()) return ServiceResponse<bool>.SuccessResponse("用户同步成功", true);

                RRoleUser roleUser = new RRoleUser
                {
                    ID = GuidUtil.NewSequentialId(),
                    RoleID = role.RoleID,
                    UserID = sysUser.UserID
                };
                RoleUserService.Add(roleUser);
            }
            catch (Exception ex)
            {
                log.LogLevel = "Error";
                log.InnerException = ex.InnerException.ToString();
                log.Message = ex.Message.ToString();
                logService.Add(log);
            }

            return ServiceResponse<bool>.SuccessResponse("用户同步成功", true);
        }

        /// <summary>
        /// 更新用户-骏客APP
        /// </summary>
        /// <param name="userjk">骏客APP用户实体</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("api/user/updateUserjk")]
        public ServiceResponse<bool> UpdateUserjk(Userjk userjk)
        {
            if (userjk == null) return ServiceResponse<bool>.SuccessResponse("用户信息不可为空", false);
            if (string.IsNullOrEmpty(userjk.LoginName) || string.IsNullOrEmpty(userjk.AgentNumber) || string.IsNullOrEmpty(userjk.Unumber) || string.IsNullOrEmpty(userjk.UserName)) return ServiceResponse<bool>.SuccessResponse("登录账号/经销商号/职员代码/职员名称 不可为空", false);
            var exist = userService.Find(x => x.LoginName == userjk.LoginName && x.UserType == UserType.UserTypeSTUDENT);
            if (exist == null) return ServiceResponse<bool>.SuccessResponse("用户不存在(登录账号+经销商号码 查询没有记录)", false);

            exist.ModifyTime = DateTime.Now;
            exist.Sex = userjk.Sex;
            exist.Unumber = userjk.Unumber;
            exist.UserName = userjk.UserName;
            exist.AccountStatus = userjk.AccountStatus;
            exist.CardNo = userjk.CardNo;

            var res = userService.Update(exist);
            if (!res) return ServiceResponse<bool>.SuccessResponse("用户更新失败，系统错误", false);
            return ServiceResponse<bool>.SuccessResponse("用户更新成功", true);
        }

        /// <summary>
        /// 禁用/启用 用户-骏客APP
        /// </summary>
        /// <param name="loginName">登录名称</param>
        /// <param name="agentNumber">经销商号</param>
        /// <param name="accountStatus">禁用/启用：0-禁用；1-启用</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("api/user/ableUserjk")]
        public ServiceResponse<bool> AbleUserjk(string loginName, string agentNumber, int accountStatus)
        {
            if (string.IsNullOrEmpty(loginName) || string.IsNullOrEmpty(agentNumber)) return ServiceResponse<bool>.SuccessResponse("登录账号/经销商号码 不可为空", false);
            var exist = userService.Find(x => x.LoginName == loginName && x.UserType == UserType.UserTypeSTUDENT);
            if (exist == null) return ServiceResponse<bool>.SuccessResponse("用户不存在(登录账号+经销商号码 查询没有记录)", false);
            exist.AccountStatus = accountStatus;

            var res = userService.Update(exist);

            if (!res) return ServiceResponse<bool>.SuccessResponse("操作失败，系统错误", false);
            return ServiceResponse<bool>.SuccessResponse("操作成功", true);
        }

        /// <summary>
        /// 删除用户-销售助手
        /// </summary>
        /// <param name="loginName">登录名称</param>
        /// <param name="agentNumber">经销商号</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, Route("api/user/deleteUserjk")]
        public ServiceResponse<bool> DeleteUserjk(string loginName, string agentNumber)
        {
            if (string.IsNullOrEmpty(loginName) || string.IsNullOrEmpty(agentNumber)) return ServiceResponse<bool>.SuccessResponse("登录账号/经销商号码 不可为空", false);
            var exist = userService.Find(x => x.LoginName == loginName && x.UserType == UserType.UserTypeSTUDENT);
            if (exist == null) return ServiceResponse<bool>.SuccessResponse("用户不存在(登录账号+经销商号码 查询没有记录)", false);

            exist.IsDelete = true;

            var res = userService.Update(exist);
            if (!res) return ServiceResponse<bool>.SuccessResponse("用户删除失败，系统错误", false);
            return ServiceResponse<bool>.SuccessResponse("用户删除成功", true);
        }
        #endregion

        [HttpGet, Route("api/user/SetCode")]
        [AllowAnonymous]
        public object SetCode()
        {
            var i = 0;
            var users = userService.FindList(o => !o.IsDelete).ToList();
            foreach (var user in users)
            {
                var inviteCode = $"{CodeHelper.CreateCodePre()}{i.ToString().PadLeft(8, '0')}";

                //邀请码生成成功，存入数据库
                tInviteCodeLogService.AddNoSaveChange(new TInviteCodeLog
                {
                    Id = Guid.NewGuid(),
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    IsDelete = false,
                    CreateUserId = CurrentUserModel.UserId,
                    UpdateUserId = CurrentUserModel.UserId,
                    InviteCode = inviteCode,
                    OrgCode = user.OrgCode,
                    UserId = user.UserID,
                    Sort = i
                });
                i++;
                user.InviteCode = inviteCode;
                userService.UpdateNoSaveChange(user);
            }

            userService.SaveChange();
            return true;
        }

        [HttpGet, Route("api/user/SetOrgCode")]
        [AllowAnonymous]
        public object SetOrgCode()
        {
            var i = tInviteCodeLogService.FindList(p => !p.IsDelete).OrderByDescending(p => p.Sort).FirstOrDefault()?.Sort ?? 0;
            var orgs = orgService.FindList(o => !o.IsDelete).ToList();
            foreach (var org in orgs)
            {
                var inviteCode = $"{CodeHelper.CreateCodePre()}{i.ToString().PadLeft(8, '0')}";

                //邀请码生成成功，存入数据库
                tInviteCodeLogService.AddNoSaveChange(new TInviteCodeLog
                {
                    Id = Guid.NewGuid(),
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    IsDelete = false,
                    CreateUserId = CurrentUserModel.UserId,
                    UpdateUserId = CurrentUserModel.UserId,
                    InviteCode = inviteCode,
                    OrgCode = org.org_code,
                    UserId = Guid.Empty,
                    Sort = i
                });
                i++;
                org.InviteCode = inviteCode;
                orgService.UpdateNoSaveChange(org);
            }

            orgService.SaveChange();
            return true;
        }
    }
}